import React, { useState, useEffect, useRef } from "react";
import { Layout, Menu, Typography, Space } from "antd";
import type { MenuProps } from "antd";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import Home from "./components/Home";
import Projects from "./components/Projects";
import Interests from "./components/Interests";
import Contact from "./components/Contact";
import "./App.css";

gsap.registerPlugin(ScrollTrigger);

const { Header, Content, Footer } = Layout;

const App: React.FC = () => {
  const [activeSection, setActiveSection] = useState("home");
  const sectionsRef = useRef<(HTMLElement | null)[]>([]);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setActiveSection(entry.target.id);
          }
        });
      },
      {
        threshold: 0.5,
        rootMargin: "-64px 0px 0px 0px",
      }
    );

    const sections = document.querySelectorAll("section");
    sections.forEach((section) => observer.observe(section));

    return () => {
      sections.forEach((section) => observer.unobserve(section));
    };
  }, []);

  useEffect(() => {
    ScrollTrigger.getAll().forEach((t) => t.kill());

    sectionsRef.current.forEach((section, index) => {
      if (!section) return;

      // 背景视差效果
      const bg = section.querySelector(".section-bg");
      if (!bg) return;

      gsap.fromTo(
        bg,
        {
          y: "-20%",
        },
        {
          y: "20%",
          ease: "none",
          scrollTrigger: {
            trigger: section,
            start: "top bottom",
            end: "bottom top",
            scrub: 1,
          },
        }
      );

      // 内容动画
      const content = section.querySelector(".section-content");
      if (!content) return;

      gsap.fromTo(
        content,
        {
          opacity: 0,
          y: 100,
        },
        {
          opacity: 1,
          y: 0,
          scrollTrigger: {
            trigger: section,
            start: "top 70%",
            end: "top 30%",
            scrub: 1,
          },
        }
      );
    });

    return () => {
      ScrollTrigger.getAll().forEach((t) => t.kill());
    };
  }, []);

  const scrollToSection = (sectionId: string) => {
    const element = document.getElementById(sectionId);
    if (element) {
      const headerHeight = 64;
      const elementPosition = element.getBoundingClientRect().top;
      const offsetPosition =
        elementPosition + window.pageYOffset - headerHeight;

      window.scrollTo({
        top: offsetPosition,
        behavior: "smooth",
      });
    }
  };

  const menuItems: MenuProps["items"] = [
    {
      key: "home",
      label: "首页",
      onClick: () => scrollToSection("home"),
    },
    {
      key: "projects",
      label: "项目",
      onClick: () => scrollToSection("projects"),
    },
    {
      key: "interests",
      label: "兴趣爱好",
      onClick: () => scrollToSection("interests"),
    },
    {
      key: "contact",
      label: "联系方式",
      onClick: () => scrollToSection("contact"),
    },
  ];

  const sectionStyle = (index: number): React.CSSProperties => ({
    width: "100%",
    height: "100vh",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    position: "relative",
    overflow: "hidden",
    // backgroundColor: `hsl(${index * 90}, 80%, 97%)`,
  });

  return (
    <Layout>
      <Header className="header">
        <div className="header-content">
          <div className="logo">MyPortfolio</div>
          <Menu
            mode="horizontal"
            theme="dark"
            items={menuItems}
            selectedKeys={[activeSection]}
          />
        </div>
      </Header>

      <Content>
        <div className="content-container">
          <Space direction="vertical" size={0} style={{ width: "100%" }}>
            {["home", "projects", "interests", "contact"].map((id, index) => (
              <section
                key={id}
                id={id}
                ref={(el) => (sectionsRef.current[index] = el)}
                style={sectionStyle(index)}
              >
                <div
                  className="section-bg"
                  style={{
                    position: "absolute",
                    top: "-20%",
                    left: 0,
                    width: "100%",
                    height: "140%",
                    backgroundColor: `hsl(${index * 90}, 70%, 85%)`,
                    zIndex: -1,
                  }}
                />
                <div className="section-content">
                  {id === "home" && <Home />}
                  {id === "projects" && <Projects />}
                  {id === "interests" && <Interests />}
                  {id === "contact" && <Contact />}
                </div>
              </section>
            ))}
          </Space>
        </div>
      </Content>

      <Footer style={{ textAlign: "center" }}>
        <Typography.Text>
          联系方式: example@email.com | GitHub: @yourusername
        </Typography.Text>
      </Footer>
    </Layout>
  );
};

export default App;
